package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.model.Group;
import cn.edu.ujs.coor.model.GroupUserRelation;
import cn.edu.ujs.coor.model.User;
import cn.edu.ujs.coor.repository.group.GroupMapper;
import cn.edu.ujs.coor.repository.group.GroupRepository;
import cn.edu.ujs.coor.repository.relation.GroupUserRelationRepository;
import cn.edu.ujs.coor.repository.relation.ProjectGroupRelationRepository;
import cn.edu.ujs.coor.repository.user.UserRepository;
import cn.edu.ujs.coor.request.IdRequest;
import cn.edu.ujs.coor.request.group.GroupAddRequest;
import cn.edu.ujs.coor.request.group.GroupConfigRequest;
import cn.edu.ujs.coor.request.group.GroupUpdateRequest;
import cn.edu.ujs.coor.response.GroupResponse;
import cn.edu.ujs.coor.util.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class GroupService extends BaseService<Group, GroupResponse> {

    @Autowired
    private GroupUserRelationRepository groupUserRelationRepository;

    @Autowired
    private ProjectGroupRelationRepository projectGroupRelationRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    public void setMapper(GroupMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setRepository (GroupRepository repository) {
        this.repository = repository;
    }

    /**
     * 根据组织编号查询
     * @param user
     * @return
     */
    public List<Group> findGroup (User user) {
        if ("admin".equals(user.getId())) {
            return this.findAll();
        }
        return ((GroupRepository)repository).findByOrganizationId(user.getOrganizationId());
    }

    /**
     * 创建分组
     * @param request
     */
    public void create (GroupAddRequest request) {
        // 创建分组
        Group group = request.convertToEntity(Group.class);
        this.repository.save(group);
    }

    /**
     * 分组详情
     * @param request
     * @return
     */
    public JSONObject info (IdRequest request) {
        Group group = this.findById(request.getId());
        JSONObject info = (JSONObject) JSONObject.toJSON(group);
        List<String> userIds = groupUserRelationRepository.findByGroupId(group.getId());
        List<User> users = userRepository.findAllById(userIds);
        info.put("users", users);
        return info;
    }

    /**
     * 更新分组
     * @param request
     */
    public void update (GroupUpdateRequest request) {
        // 创建分组
        Group group = this.findById(request.getId());
        if (group == null) {
            throw new CoorException("er_000002", "该分组不存在");
        }
        BeanUtil.copyBeanIgnoreNull(group, request);
        this.repository.save(group);
    }

    public void config (GroupConfigRequest request) {
        Group group = this.findById(request.getId());
        if (group == null) {
            throw new CoorException("er_000002", "该分组不存在");
        }
        // 更新分组用户关联
        groupUserRelationRepository.deleteByGroupId(request.getId());
        Set<String> ids = new HashSet<>();
        if (request.getUserIds() != null) {
            ids.addAll(request.getUserIds());
        }
        // 关联
        if (request.getGroupIds() != null && request.getGroupIds().size() > 0) {
            for (String groupId : request.getGroupIds()) {
                ids.addAll(groupUserRelationRepository.findByGroupId(groupId));
            }
        }
        // 分组用户关联
        for (String userId : ids) {
            GroupUserRelation relation = GroupUserRelation
                    .builder()
                    .groupId(group.getId())
                    .userId(userId)
                    .build();
            groupUserRelationRepository.save(relation);
        }
    }

    /**
     * 删除分组
     * @param request
     */
    public void delete (IdRequest request) {
        // 创建分组
        Group group = this.findById(request.getId());
        if (group == null) {
            throw new CoorException("er_000002", "该分组不存在");
        }
        // 删除分组用户关联
        groupUserRelationRepository.deleteByGroupId(request.getId());
        projectGroupRelationRepository.deleteByGroupId(request.getId());
        // 删除分组记录
        this.deleteById(request.getId());
    }
}
